<template>
  <div class="app-container">

    <el-row :gutter="20">
      <!--区域数据-->
      <el-col :span="4" :xs="24">
        <div class="box-card">
          <div class="head-container">
            <el-input v-model="filterText" placeholder="请输入分类名称" clearable size="small" prefix-icon="el-icon-search"
              style="margin-bottom: 20px" />
          </div>
          <div class="head-container">
            <el-tree :data="deviceClass" :props="defaultProps" :expand-on-click-node="false"
              :filter-node-method="filterNode" ref="tree" node-key="id" default-expand-all highlight-current
              @node-click="handleNodeClick">
              <div class="custom-tree-node" slot-scope="{ node, data }">
                <div>{{ node.label }}</div>
                <div>
                  <i class="el-icon-edit" @click.stop="() => setEditRegion(data)"></i>
                  <i class="el-icon-delete" style="margin-left: 10px;"
                    @click.stop="() => handleDeleteInfoClass(data)"></i>
                </div>
              </div>
            </el-tree>
          </div>
        </div>
      </el-col>


      <el-col :span="20" :xs="24">
        <transition>
          <div v-show="showSearch" class="mb-[10px]">
            <el-card shadow="hover">
              <el-form ref="queryFormRef" :model="queryParams" :inline="true">
                <el-form-item label="设备名称">
                  <el-input v-model="queryParams.deviceName" placeholder="请输入设备名称" clearable
                    @keyup.enter="handleQuery" />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                  <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                </el-form-item>
              </el-form>
            </el-card>
          </div>
        </transition>

        <el-card shadow="hover">
          <template #header>
            <el-row :gutter="10">
              <el-col :span="1.5">
                <el-button v-hasPermi="['iot:device:add']" type="primary" plain icon="Plus"
                  @click="add">新增设备分类</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button v-hasPermi="['iot:device:add']" type="primary" plain icon="Plus"
                  @click="handleAdd">新增设备</el-button>
              </el-col>
              <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
            </el-row>
          </template>

          <el-table ref="menuTableRef" v-loading="loading" :data="deviceList" row-key="menuId" height="650"
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" :default-expand-all="isExpandAll">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="deviceName" label="设备名称"></el-table-column>
            <el-table-column prop="deviceType" label="设备类型">
              <template #default="scope">
                <el-tag class="ml-2">
                  {{ getDeviceTypeName(scope.row.deviceType) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="deviceMac" label="MAC地址"></el-table-column>
            <el-table-column prop="deviceIp" label="设备IP"></el-table-column>
            <el-table-column prop="deviceStatus" label="设备状态">
              <template #default="scope">
                <el-tag class="ml-2" type="danger" v-if="scope.row.deviceStatus == '0'">离线</el-tag>
                <el-tag class="ml-2" type="success" v-if="scope.row.deviceStatus == '1'">正常</el-tag>
                <el-tag class="ml-2" type="warning" v-if="scope.row.deviceStatus == '2'">停用</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="通讯方式" prop="deviceCommunication"></el-table-column>
            <el-table-column label="更新时间" prop="updateTime"></el-table-column>
            <el-table-column fixed="right" label="操作" width="250">
              <template #default="scope">
                <el-tooltip content="预览" placement="top">
                  <el-button size="mini" type="text" icon="el-icon-view" @click="viewApp">预览</el-button>
                </el-tooltip>
                <el-tooltip content="修改" placement="top">
                  <el-button v-hasPermi="['iot:device:edit']" size="mini" type="text" icon="el-icon-edit"
                    @click="handleUpdate(scope.row)">修改</el-button>
                </el-tooltip>
                <!-- <el-tooltip content="设置模板" placement="top">
              <el-button v-hasPermi="['system:menu:add']" size="mini" type="text"
                icon="el-icon-edit-outline">设置模板</el-button>
            </el-tooltip> -->
                <el-tooltip content="删除" placement="top">
                  <el-button v-hasPermi="['iot:device:remove']" size="mini" type="text" icon="el-icon-delete"
                    @click="handleDelete(scope.row)">删除</el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </el-card>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize" @pagination="getList" />

        <el-dialog :visible.sync="dialog.visible" :title="dialog.title" destroy-on-close append-to-body width="750px">
          <el-form ref="menuFormRef" :model="initFormData" :rules="rules" label-width="130px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="设备名称：" prop="deviceName">
                  <el-input v-model="initFormData.deviceName" placeholder="请输入设备名称" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="设备类型：" prop="deviceType">
                  <el-select v-model="initFormData.deviceType" placeholder="请选择">
                    <el-option v-for="(item, index) in deviceClass" :key="index" :label="item.name" :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="MAC地址：" prop="deviceMac">
                  <el-input v-model="initFormData.deviceMac" placeholder="请输入MAC地址" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="设备IP：" prop="deviceIp">
                  <el-input v-model="initFormData.deviceIp" placeholder="请输入设备IP" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="设备状态：" prop="deviceStatus">
                  <el-select v-model="initFormData.deviceStatus" placeholder="请选择设备状态">
                    <el-option label="离线" value="0" />
                    <el-option label="在线" value="1" />
                    <el-option label="停用" value="2" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="通讯方式：" prop="deviceCommunication">
                  <el-select v-model="initFormData.deviceCommunication" placeholder="请选择通讯方式">
                    <el-option label="MQTT" value="MQTT" />
                    <el-option label="WebSocket" value="WebSocket" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="启用人脸：" prop="deviceCommunication">
                  <el-radio-group v-model="initFormData.isFace">
                    <el-radio :label="0">不启用</el-radio>
                    <el-radio :label="1">启用</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="initFormData.isFace == 1">
                <el-form-item label="APP_ID：">
                  <el-input v-model="initFormData.appId" placeholder="请输入人脸APP_ID" />
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="initFormData.isFace == 1">
                <el-form-item label="ACTIVE_KEY：">
                  <el-input v-model="initFormData.activeKey" placeholder="请输入人脸ACTIVE_KEY" />
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="initFormData.isFace == 1">
                <el-form-item label="SDK_KEY：">
                  <el-input v-model="initFormData.sdkKey" placeholder="请输入人脸SDK_KEY" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button type="primary" @click="submitForm">确 定</el-button>
              <el-button @click="cancel">取 消</el-button>
            </div>
          </template>
        </el-dialog>

        <el-dialog v-model="dialogLook.visible" :title="dialogLook.title" destroy-on-close append-to-body width="750px">
          <div>
            <img src="../../../assets/images/pb.jpg" style="width: 100%;height: 400px;">
          </div>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="cancel">关 闭</el-button>
            </div>
          </template>
        </el-dialog>
      </el-col>
    </el-row>

    <el-drawer :title="title" :visible.sync="drawer">
      <el-form :model="ruleForm" :rules="rulesClass" ref="rulesClass" label-width="100px" class="demo-ruleForm">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="ruleForm.name"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitFormClass('rulesClass')">立即创建</el-button>
          <el-button @click="resetForm('rulesClass')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script>
import { list, addDevice, updateDevice, deleteDevice } from '@/api/information/index';
import { listclass, addclass, Updateclass, delclass } from "../../../api/information/deviceClass.js"
export default {
  data() {
    return {
      filterText: '',
      title: "新增分类",
      ruleForm: {
        name: ''
      },
      ruleFormQuery: {
        name: '',
        pageNum: 1,
        pageSize: 10
      },
      rulesClass: {
        name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      },
      drawer: false,
      deviceClass: [],
      defaultProps: {
        children: "children",
        label: "name"
      },
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deviceName: '',
        deviceStatus: ''
      },
      deviceList: [],
      loading: true,
      showSearch: true,
      isExpandAll: false,
      dialog: {
        visible: false,
        title: ''
      },
      dialogLook: {
        visible: false,
        title: '设备实时'
      },
      initFormData: {
        id: '',
        deviceName: '',
        deviceType: '',
        deviceMac: '',
        deviceIp: '',
        deviceStatus: '',
        deviceCommunication: '',
        appId: '',
        activeKey: '',
        sdkKey: '',
        isFace: 0
      },
      rules: {
        deviceName: [{ required: true, message: '设备名称不能为空', trigger: 'blur' }],
        deviceIp: [{ required: true, message: '设备IP不能为空', trigger: 'blur' }],
        deviceMac: [{ required: true, message: '设备MAC不能为空', trigger: 'blur' }],
        deviceType: [{ required: true, message: '设备类型不能为空', trigger: 'blur' }],
        deviceCommunication: [{ required: true, message: '设备通讯方式不能为空', trigger: 'change' }],
        deviceStatus: [{ required: true, message: '设备状态不能为空', trigger: 'change' }]
      },
      menuTableRef: null,
      total: 0
    };
  },
  watch: {
    // 根据名称筛选部门树
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  methods: {
    getDeviceTypeName(id) {
      const type = this.deviceClass.find(item => item.id === id);
      return type ? type.name : '未知类型';
    },
    // 筛选节点
    filterNode(value, data) {
      console.log(value, data)
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    setEditRegion(data) {
      this.ruleForm = data
      this.drawer = true
      this.title = "修改分类"
    },
    subUpdate() {
      Updateclass(this.ruleForm).then((res) => {
        this.$message({
          message: '修改成功',
          type: 'success'
        });
        this.drawer = false
        this.getList()
        this.resetForm()
        this.ruleFormQuery.name = ""
        this.getListInfoClass()
      });
    },
    handleDeleteInfoClass(val) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delclass(val.id).then((res) => {
          this.$message({
            message: '删除成功',
            type: 'success'
          });
          this.ruleFormQuery.name = ""
          this.getListInfoClass()
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    submitFormClass(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.title == "修改分类") {
            this.subUpdate()
          } else {
            this.addinfo()
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    addinfo() {
      addclass(this.ruleForm).then((res) => {
        this.$message({
          message: '新增成功',
          type: 'success'
        });
        this.ruleFormQuery.name = ""
        this.drawer = false
        this.getList()
        this.resetForm()
        this.getListInfoClass()
      });
    },
    resetForm(formName) {
      this.ruleForm = {
        name: ''
      }
    },
    add() {
      this.drawer = true
      this.title = "新增分类"
    },
    getListInfoClass() {
      listclass(this.ruleFormQuery).then((res) => {
        this.deviceClass = res.rows
      });
    },
    handleNodeClick(val) {
      console.log(val)
      this.queryParams.deviceType = val.id
      this.getList()
    },
    async getList() {
      this.loading = true;
      const res = await list(this.queryParams);
      this.deviceList = res.rows;
      this.total = res.total
      this.loading = false;
    },
    cancel() {
      this.$nextTick(() => {
        this.reset();
      })
      this.dialog.visible = false;
      this.dialogLook.visible = false;
    },
    reset() {
      this.$refs.menuFormRef.resetFields();
    },
    handleQuery() {
      this.getList();
    },
    resetQuery() {
      this.$refs.queryFormRef.resetFields();
      this.handleQuery();
    },
    handleAdd() {
      this.dialog.visible = true;
      this.dialog.title = '添加设备';
      this.reset();
    },
    async handleUpdate(row) {
      this.dialog.visible = true;
      this.dialog.title = '修改设备';
      this.$nextTick(() => {
        this.reset();
        this.initFormData = { ...row };
      })
    },
    submitForm() {
      this.$refs.menuFormRef.validate(async (valid) => {
        if (valid) {
          if (this.initFormData.id) {
            updateDevice(this.initFormData).then((res) => {
              this.infoList = res.rows;
              this.getList();
              this.getListInfoClass()
            });
          } else {
            addDevice(this.initFormData).then((res) => {
              this.infoList = res.rows;
              this.getList();
            });
          }
          this.$modal.msgSuccess('操作成功');
          this.dialog.visible = false;
        }
      });
    },
    handleDelete(row) {
      this.$confirm(`是否确认删除名称为"${row.deviceName}"的数据项?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteDevice(row.id).then((res) => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.getList();
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    viewApp() {
      this.dialogLook.visible = true;
    }
  },
  mounted() {
    this.getList();
    this.getListInfoClass()
    this.loading = false;
  }
};
</script>
<style>
.demo-form-inline {
  padding: 20px;
}

.btn {
  width: 100%;
  text-align: right;
}

.box-card {
  height: 100vh;
  border-right: 1px solid #eee;
  padding: 10px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 12px;
  padding-right: 8px;
}

.el-tree-node__expand-icon.is-leaf {
  display: none;
}
</style>
